<!--发言黑名单管理-->
<script lang="ts" setup>
import {onMounted, ref, watch} from "vue";
import {useUserStore} from "../../store/UserStore.ts";
import type {TinyUserInfo} from "../../network/types/User.ts";
import UserRoute from "../routes/UserRoute.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {BlockConfig} from "../../network/types/BlockConfig.ts";
import {useRoute} from "vue-router";

const userStore = useUserStore();
const route = useRoute();
// 屏蔽的关键字
const keywords = ref<string[]>()
// 屏蔽的用户
const users = ref<TinyUserInfo[]>()
const loading = ref(false)

const list = (force: boolean = false) => {
  loading.value = true
  userStore.blockConfigGet(force).then(res => {
    keywords.value = res.keywords
    users.value = res.users
    loading.value = false
  }).catch(r => {
    console.error(r)
    list()
  })
}

const save = () => {
  loading.value = true
  const config = new BlockConfig();
  config.keywords = keywords.value || []
  config.users = users.value || []
  userStore.blockConfigSet(config).then(res => {
    ElMessage.success(res)
    loading.value = false
  })
}

const addKeyword = () => {
  // 弹窗要求输入关键字
  ElMessageBox.prompt("请输入关键字，多个用空格隔开", "添加黑名单").then(({value}) => {
    const texts = value.split(' ').filter(i => i);
    keywords.value?.push(...texts)
  })
}

const addUser = () => {
  // 弹窗要求输入用户id或用户名，查询该用户信息，用户存在则添加到黑名单
  ElMessageBox.prompt("请输入用户id或用户名", "添加黑名单").then(async ({value}) => {
    const userId = (await userStore.detailHtmlText(value)).userId;
    if (!userId) {
      ElMessage.error("用户不存在")
      return
    }
    // 用户存在，添加到黑名单
    users.value?.push({
      userId,
      username: value
    })
  })
}

onMounted(() => {
  list()
})
watch(route, () => {
  list()
})

</script>

<template>
  <div v-loading="loading" class="route-root" style="text-align: start">
    <el-button-group type="success">
      <el-button @click="list(true)">刷新</el-button>
      <el-button @click="save">保存</el-button>
    </el-button-group>

    <h4>关键字</h4>
    <div>
      <el-button class="config-tag" size="small" type="success" @click="addKeyword">+</el-button>
      <el-tag v-for="(key,index) in keywords" class="config-tag " closable effect="dark" @close="keywords?.splice(index,1)">{{ key }}</el-tag>
    </div>

    <h4>用户</h4>
    <div>
      <el-button class="config-tag" size="small" type="success" @click="addUser">+</el-button>
      <el-tag v-for="(user,index) in users" class="config-tag" closable effect="dark" @close="users?.splice(index,1)">
        <user-route :user-id="user.userId" :username="user.username ">{{ user.username }}</user-route>
      </el-tag>
    </div>
  </div>
</template>

<style scoped>
.config-tag {
  margin-right: 3px;
}
</style>